<?php

class Attachment extends AppModel {
	var $name= 'Attachment';
	var $recursive = 0;
	
	//ACL this is a controlled object ACO
	var $actsAs = array('Acl' => array('type' => 'controlled'));
	
	var $virtualFields = array(
    'full_name' => 'CONCAT(Application.lastname, "_", Application.firstname, "_", Attachment.doc_type, "_", Attachment.file_name)'
  );

	
	function parentNode() {
		if (!$this->id && empty($this->data)) {
			return null;
		}
		if (isset($this->data['Attachment']['application_id'])) {
			$appId = $this->data['Attachment']['application_id'];
		} else {
			$appId = $this->field('application_id');
		}
		if (!$appId) {
			return null;
		} else {
			return array('Application' => array('id' => $appId));
		}
	}

function beforeSave($options) {
	if(isset($this->data['Attachment']['content'])) {
		$file = $this->data['Attachment']['content'];
		$file_contents = file_get_contents($file['tmp_name']);
		if($file_contents) {
			$file_contents = base64_encode($file_contents);
			$this->set('content', $file_contents);
			$this->set('mime_type', $file['type']);
			$this->set('file_name', $file['name']);
			$this->set('file_size', $file['size']);
			return true;
		}
	}
	return false;
}

function afterFind($results, $primary) {
	//if this was the primary find.
	if($primary) {
		//for each result, which contains a content field.
		//unencode the content field.
		foreach($results as $line => $result) {
			if(isset($result['Attachment']['content'])) {
				$results[$line]['Attachment']['content'] = base64_decode($result['Attachment']['content']);
			}
		}
	}
	return $results;
}
	
/**
* Validation Criteria.
*	
*/
var $validate = array(
		'id' => array(
		  'limitAts' => array(
			  'rule' => array('limitCount', 15),
			  'message' => 'You are limited to 15 attachments.'
			)
		),
	  'doc_type' => array(
		  'notempty' => array(
			  'rule' => array('notempty'),
			  'message' => 'A doctype is required.'
			)
		),
		'content' => array(
			'upload' => array(
			  'rule' => array('isUploadedFile'),
			  'message' => 'Not an a valid file upload.'
			),
			'filetype' => array(
				'rule' => array(
					'isValidFileType', array(
						'application/pdf',                // pdf
          	'application/x-pdf', 
          	'application/acrobat', 
          	'text/pdf',
          	'text/x-pdf', 

          	'text/plain',                     // text
          	'application/rtf',
						'text/richtext',
						'text/rtf',
						'application/msword'
					)
				),
				'message' => 'Not a valid file type.'
			)
		)
	); 
	
/**
* START ASSOCIATION INFORMATION
******************************************************************************
*/
 	
	var $belongsTo = array(
		'Application' => array(
			'className' => 'Application',
			'foreignKey' => 'application_id'
		),
		'Reference' => array(
			'className' => 'Reference',
			'foreignKey' => 'reference_id'
		)
	); //end belongsTo array.

}